package com.document.controll;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import com.document.model.Directory;
import com.document.model.DirectoryRight;
import com.document.model.Org;
import com.document.model.PageModel;
import com.document.model.User;
import com.document.utils.SystemContext;

@IocBean
@InjectName
public class DirectoryAction extends BaseAction {
	
	@Ok("jsp:pages.directory.directoryList")
	@At("/directory/list")
	public void list(@Param("currentPage") int currentPage,HttpServletRequest req) {
		User user = (User) req.getSession().getAttribute("userInfo");
		if(currentPage == 0){
			currentPage = 1;
		}
		Cnd cnd = Cnd.where("createuserid","=", user.getId());
		String dirCode = req.getParameter("dircode");
		String dirName = req.getParameter("dirname");
		String startTime = req.getParameter("starttime");
		String endTime = req.getParameter("endtime");
		if(dirName != null && !"".equals(dirName)){
			cnd.and("dirname", "like", "%" + dirName + "%");
			req.setAttribute("dirName", dirName);
		}
		if(dirCode != null && !"".equals(dirCode)){
			cnd.and("dircode", "like", "%" + dirCode + "%");
			req.setAttribute("dirCode", dirCode);
		}
		if(startTime != null && endTime != null && !"".equals(startTime) && !"".equals(endTime)){
			cnd.and("createtime", ">=", startTime);
			cnd.and("createtime", "<=", endTime);
			req.setAttribute("startTime", startTime);
			req.setAttribute("endTime", endTime);
		}
		List<Directory> list = basicDao.searchByPage(Directory.class, 
				cnd, currentPage, SystemContext.PAGE_SIZE);	
		int len = list.size();
		if(len > 0 && len <= SystemContext.PAGE_SIZE){
			for(int i = list.size();i < SystemContext.PAGE_SIZE;i++){
				list.add(new Directory());
			}
			int count = basicDao.searchCount(Directory.class,cnd);	
			int maxPage = basicDao.maxPageSize(count, SystemContext.PAGE_SIZE);	
			PageModel<Directory> pm = new PageModel<Directory>(list, maxPage);
			req.setAttribute("navid", 0);
			req.setAttribute("pm", pm);
		}
	}
	
	@At("/directory/directoryExists")
	public void directoryExists(@Param("dirId") int dirId,@Param("dirCode") String dirCode,HttpServletResponse resp){
		Directory dir = basicDao.findByCondition(Directory.class, Cnd.where("dircode", "=", dirCode).and("dirid", "!=", dirId));
		String rvt = "{exists:false}";
		if(dir != null && dir.getDirCode() != null && !"".equals(dir.getDirCode())){
			rvt = "{exists:true}";
		}
		write(resp,rvt);
	}
	
	@At("/directory/add")
	public void add(@Param("::dir.") Directory dir,HttpServletRequest req,HttpServletResponse resp){
		User user = (User) req.getSession().getAttribute("userInfo");
		dir.setCreateUserId(user.getId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		dir.setCreateTime(sdf.format(new Date()));
		dir.setStatus("1");
		dir.setDispose("1");
		dir.setPath(dir.getDirCode());
		dir = basicDao.save(dir);
		String rvt = "{success:false}";
		if(dir.getId() > 0){
			rvt = "{success:true}";
		}
		write(resp, rvt);
	}
	
	@At("/directory/update")
	public void update(@Param("::dir.") Directory dir,HttpServletResponse resp){
		Directory _dir = basicDao.find(dir.getId(), Directory.class);
		_dir.setDirName(dir.getDirName());
		_dir.setDirCode(dir.getDirCode());
		_dir.setRemark(dir.getRemark());
		_dir.setPath(dir.getDirCode());
		boolean success = basicDao.update(_dir);
		write(resp,"{success:" + success + "}");
	}
	
	@At("/directory/delete")
	public void delete(@Param("dirId") int dirId,HttpServletResponse resp){
		boolean success = basicDao.delById(dirId, Directory.class);
		write(resp,"{success:" + success + "}");
	}
	
	@At("/directory/findDirectoryById")
	public void findDirectoryById(@Param("dirId") int dirId,HttpServletResponse resp){
		Directory dir = basicDao.find(dirId, Directory.class);
		super.write(resp, Json.toJson(dir, JsonFormat.full()));
	}
	
	@At("/directory/publish")
	public void publish(@Param("dirId") int dirId,@Param("status") String status,HttpServletResponse resp){
		Directory dir = basicDao.find(dirId, Directory.class);
		if("1".equals(status)){
			status = "2";
		}else if("2".equals(status)){
			status = "1";
		}else{
			status = "";
		}
		dir.setStatus(status);
		boolean success = basicDao.update(dir);
		write(resp,"{success:" + success + ",status:'" + status + "',dispose:'" + dir.getDispose() + "'}");
	}
	
	@At("/directory/dispose")
	public void dispose(@Param("dirId") int dirId,@Param("dispose") String dispose,HttpServletResponse resp){
		Directory dir = basicDao.find(dirId, Directory.class);
		if("1".equals(dispose)){
			dispose = "2";
		}else if("2".equals(dispose)){
			dispose = "1";
		}else{
			dispose = "";
		}
		dir.setDispose(dispose);
		boolean success = basicDao.update(dir);
		write(resp,"{success:" + success + ",dispose:" + dispose + "}");
	}
	
	@Ok("jsp:pages.directory.rightPage")
	@At("/directory/listRight")
	public void listRight(@Param("dirId") int dirId,HttpServletRequest req){
		Sql sql = Sqls.queryRecord("SELECT b.userid,b.username,b.fullname,t.dirrigid FROM b_user b"
				+ " left join t_directory_right t on b.userid=t.userid and t.dirid="
				+ dirId + " where b.userstatus='1'");
		sql.setCallback(new SqlCallbackImpl());
		basicDao.excute(sql);	
		HashMap map = (HashMap) sql.getResult();
		req.setAttribute("leftList", map.get("leftList"));
		req.setAttribute("rightList", map.get("rightList"));
	}
	
	@At("/directory/saveRight")
	public void saveRight(@Param("dirId") int dirId,@Param("userIds") int[] userIds,final HttpServletResponse resp){
		final int _dirId = dirId;
		final int[] _userIds = userIds;
		/*Trans.exec(new Atom() {
			public void run() {*/
				String rvt = "{success:true}";
				try{
					basicDao.delete("t_directory_right", Cnd.where("dirid", "=",_dirId));
					DirectoryRight dr = null;
					List<DirectoryRight> list = new ArrayList<DirectoryRight>();
					for(int userId : _userIds){
						dr = new DirectoryRight();
						dr.setDirid(_dirId);
						dr.setUserId(userId);
//						basicDao.save(dr);
						list.add(dr);
					}
					basicDao.save(list);
				}catch(Exception e){
					rvt = "{success:false}";
				}
				write(resp, rvt);
		/*	}
		});*/
	}
	
	private class SqlCallbackImpl implements SqlCallback{

		public Object invoke(Connection conn, ResultSet rs, Sql sql)
				throws SQLException {
			List<User> list1 = new ArrayList<User>();//待选择
			List<User> list2 = new ArrayList<User>();//已选择
			User user = null;
			int dirrigid;
			while (rs.next()) {
				user = new User();
				user.setId(rs.getInt("userid"));
				user.setUserName(rs.getString("username"));
				user.setFullName(rs.getString("fullname"));
				dirrigid = rs.getInt("dirrigid");
				if(dirrigid > 0){
					list2.add(user);
				}else{
					list1.add(user);
				}
			}
			HashMap rvt = new HashMap();
			rvt.put("leftList", list1);
			rvt.put("rightList", list2);
			return rvt;
		}
	}	
}
